package com.cloud.thelen.wallpaper.Utils;

import android.content.Context;
import android.widget.Toast;

import java.io.File;

public class DeleteFile {

    private Context context;


    public static boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
//            Toast.makeText(context, "Delete the file failure:" + delFile + "File not found！", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            if (file.isFile())
                return deleteSingleFile(delFile);
            else
                return deleteDirectory(delFile);
        }
    }

    public static boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
//                Toast.makeText(context, "Delete the file" + filePath$Name + "failure！", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
//            Toast.makeText(context, "Delete the file failure：" + filePath$Name + "File not found！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    public static boolean deleteDirectory(String filePath) {
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
//            Toast.makeText(context, "Failed to delete a directory：" + filePath + "File not found！", Toast.LENGTH_SHORT).show();
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                flag = deleteSingleFile(file.getAbsolutePath());
                if (!flag)
                    break;
            }
            else if (file.isDirectory()) {
                flag = deleteDirectory(file
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
//            Toast.makeText(context, "Failed to delete a directory！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (dirFile.delete()) {
            return true;
        } else {
//            Toast.makeText(context, "Delete the directory：" + filePath + "failure！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}
